<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        offset="50"
      >
        <ArticleIten
          v-for="val in List"
          :key="val.art_id"
          :Item="val"
          @disLikeEV="disLikeFn"
          @reportEV="reportFn"
          @click.native='itemClickFn(val.art_id)'
        >
        </ArticleIten>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleIten from '../../../components/ArticleItem.vue'
import { getAllArticleListAPI, dislikeArticleAPI, reportArticleAPI } from '@/api'
import { Notify } from 'vant'

export default {
  props: {
    // 频道id数据
    Id: Number
  },
  data () {
    return {
      List: [], // 文章列表数据
      loading: false, // 底部加载状态
      finished: false, // 底部完成状态
      theTime: (new Date()).getTime(), // 用于分页
      isLoading: false// 顶部加载状态
    }
  },
  components: { ArticleIten },
  async created () { this.getArticleListFn() },
  methods: {
    // 封装发请求的方法
    async getArticleListFn () {
      // 获取文章列表（根据频道id获取）
      const res = await getAllArticleListAPI(
        {
          id: this.Id,
          time: this.theTime
        }
      )
      this.List = [...this.List, ...res.data.data.results]// ，更新数据
      this.theTime = res.data.data.pre_timestamp// pre_timestamp下一篇文章的时间戳，后台返回0-9条数，并且携带第10条pre_timestamp值返回
      this.loading = false// 将状态改变回来
      if (res.data.data.pre_timestamp === null) { // 本次回来的数据是最后，没有下一段数据
        this.finished = true
      }
      this.isLoading = false// 顶部加载状态改为false
    },
    // 底部加载事件
    async onLoad () {
      if (this.List.length === 0) {
        this.loading = false
        return
      }
      this.getArticleListFn()
    },
    // 顶部刷新事件
    async onRefresh () {
      this.List = []
      this.theTime = (new Date()).getTime()
      this.getArticleListFn()
    },
    // 反馈-不敢兴趣-（子组件向父组件传参id值）
    async disLikeFn (id) {
      // try+catch:用户捕获同步代码的异常
      try {
        await dislikeArticleAPI(id)
        // console.log(res)
        Notify({ type: 'success', message: '反馈成功' })
      } catch (error) {
        console.log('401错误')
      }
    },
    // 二级反馈-垃圾内容-（子组件向父组件传参id值，类型id）
    async reportFn (id, typeId) {
      await reportArticleAPI({ id, typeId })
      Notify({ type: 'success', message: '举报成功' })
    },
    // 文章单元格-点击跳转到文章详情
    itemClickFn (id) {
      this.$router.push({ path: `/detail?art_id=${id}` })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
